﻿package Core
{	
	import com.junkbyte.console.Cc;
	
	import GameUtils.GameDataEvent;
	import GameUtils.UserLoader;
	
	import social.VKontakte.VKProvider;
	import social.VKontakte.VKEvents;
	import social.VKontakte.VKUserRequest;
	import social.VKontakte.VKProfileEvent;	
	import social.VKontakte.VKUserInfo;	
	import social.VKontakte.VKUserFields;
	import social.SocialDataEvent;
	
	import MySQL.MySQLProvider;
	
	import flash.events.EventDispatcher;		
	import flash.events.Event;			
	import flash.system.Security;		
	
	public class GameConnector extends EventDispatcher 
	{
		private const CLocalSettings:String = 'http://62.212.69.47/game.xml';
		
		private var FGame:Game;
		private var FSocialProvider:VKProvider;
		private var FProfile:VKUserInfo;
		//Game debug mode flag
		private var FDebugMode:Boolean;	
		private var FMySQLProvider:MySQLProvider;		
		
		public function GameConnector(AGame:Game):void
		{
			FGame = AGame;			
			with(FGame.TracksLoader)
				addEventListener(ALL_XMLS_LOADED, OnGameSpecificDataLoaded);
						
			FMySQLProvider = new MySQLProvider(AGame);
			FMySQLProvider.addEventListener(FMySQLProvider.PLAYER_INFO_LOADED, OnMySQLPlayerData);
			AGame.MySQL = FMySQLProvider;
		}		
		
		private function UpdateSecurity(APath:String):void
		{
			var vHost:String = APath.substr(7, APath.length).split('.')[0];
			Security.loadPolicyFile("http://" + vHost + ".vkontakte.ru/crossdomain.xml");
			Security.loadPolicyFile("http://" + vHost + ".vk.com/crossdomain.xml");
		}
		
		public function Start():void
		{
			if(FGame.parent is GameLoader)
			{
				/* NETWORK MODE */
				FDebugMode = false;
				try
				{
					FGame.Settings = (FGame.parent as GameLoader).Settings;
					FGame.Provider = (FGame.parent as GameLoader).Provider;
					FProfile = (FGame.parent as GameLoader).Profile;
					//Stage 1 - Loading XML Tracks data
					LoadGameSpecificData();
				}
				catch(vError:Error)
				{
					Cc.log(vError.message);
				}
			}
			else
			{
				/* LOCAL TEST MODE */			
				FDebugMode = true;
				SetupConsole();				
				FGame.Settings = new GameSettings(CLocalSettings);
				with(FGame.Settings)
				{					
					addEventListener(DATA_LOADED, LoadGameSpecificData);
					Load();
				}
			}		
		}
		
		//Stage 1 - Loading XML Tracks data
		private function LoadGameSpecificData(e:Event = null):void
		{
			FGame.Settings.removeEventListener(FGame.Settings.DATA_LOADED, LoadGameSpecificData);
			
			UpdateSecurity(FGame.Settings.ClientURL);
			FGame.LoadTracksData();
			FGame.Preloader.Percent = 0.2;
		}
		
		//Stage 2.1 - Connect to Social network if debugging
		private function OnGameSpecificDataLoaded(e:Event):void
		{
			if(FDebugMode)
			{
				FSocialProvider = new VKProvider(FGame.stage);				
				FSocialProvider.addEventListener(VKEvents.VK_PROFILE_LOADED, OnCurrentUserProfile);
				FSocialProvider.Connect();				
				
				FGame.Provider = FSocialProvider;				
				Cc.addSlashCommand('wv', FSocialProvider.RequestWithdrawVoices, 'Withdraw voices test');
				
				//Requesting basic user info
				var vRequest:VKUserRequest = new VKUserRequest(FSocialProvider.UserID);				
				vRequest.Add(VKUserFields.PhotoMedium);
				FSocialProvider.RequestUserInfo(vRequest);
			}
			else			
				ParseProfile(FProfile);
				
			FGame.Preloader.Percent = 0.4;
		}	
		
		//Stage 2.2 - Load player info from MySQL
		private function OnCurrentUserProfile(e:VKProfileEvent):void
		{
			FSocialProvider.removeEventListener(VKEvents.VK_PROFILE_LOADED, OnCurrentUserProfile);
			
			FProfile = e.VKProfile;
			ParseProfile(FProfile);
		}
		//Stage 3 - Parsing VK profile, init UserLaoder
		private function ParseProfile(AProfile:VKUserInfo):void
		{
			FGame.User.UID = FGame.UserID;
			FGame.User.Name = AProfile.FirstName + ' ' + AProfile.LastName;
			FGame.User.Photo = AProfile.PhotoMedium;
			FGame.Profile.PhotoURL = AProfile.PhotoMedium;
			FGame.Statistic.PhotoURL = AProfile.PhotoMedium;
			FMySQLProvider.LoadPlayerInfo(FGame.UserID);
			
			FGame.UsersLoader = new UserLoader(FGame.MySQL, FGame.Provider);
			
			FGame.Preloader.Percent = 0.6;
		}
		
		//Stage 4 - parsing MySQL profile, getting server Time
		private function OnMySQLPlayerData(e:GameDataEvent):void
		{
			FMySQLProvider.removeEventListener(FMySQLProvider.PLAYER_INFO_LOADED, OnMySQLPlayerData);
			
			FGame.User.Fill(e.Data as XML);
			FGame.Profile.Equipment = FGame.User.CurrentEquipment;
			FGame.Shop.PlayerItems = FGame.User.Items; 
			FGame.InterfaceMenu.Money = FGame.User.Money.toString();
			FGame.InterfaceMenu.Rating = FGame.User.Rating;
			FGame.Gameplay.Theme = FGame.User.Theme;
			FGame.Gameplay.Visualization = FGame.User.Visualization;
			FGame.Profile.Update();
			
			FGame.Provider.AutorizationScript = FGame.Settings.VKAutorization;
			FGame.Provider.SecurityRequestsScript = FGame.Settings.VKRequest;
			FGame.Provider.addEventListener(VKEvents.VK_SERVER_TIME, OnServerTime);
			FGame.Provider.RequestTime();
			
			FGame.Preloader.Percent = 0.7;
		}
		
		//Stage 5 - Connecting to Java multiplayer server
		private function OnServerTime(e:SocialDataEvent):void
		{
			FGame.User.NewTime = int(e.Data);
			FGame.UpdateProfile();
			
			FGame.MultiplayerClient.Connect();
			FGame.Preloader.Percent = 0.8;
		}
		
		private function SetupConsole():void
		{
			Cc.config.style.backgroundAlpha = 0.8;			
			Cc.startOnStage(FGame, "`");
			Cc.width = FGame.stage.stageWidth;
			Cc.fpsMonitor = true;
			Cc.commandLine = true;
			Cc.config.commandLineAllowed = true;
			Cc.config.style.topMenu = false;
			Cc.addSlashCommand('hm', FGame.HideMessage, 'Use it to hide current game message');			
		}
		
		public function get IsDebugging():Boolean
		{
			return FDebugMode;
		}
	}	
}
